package easy

import (
	"bufio"
	"fmt"
	"os"

	"gitee.com/haodreams/libs/fixedlist"
)

// 查询文件最后几行的数据
func Tail(name string, size int, isDesc bool) (lines []string, err error) {
	f, err := os.Open(name)
	if err != nil {
		return
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return
	}
	endOffset := 20 * 1024
	if fi.Size() > int64(endOffset) {
		f.Seek(0, int(fi.Size())-endOffset)
	}
	buf := bufio.NewReader(f)
	queue := fixedlist.NewFixList[string](size)
	for line, err := buf.ReadString('\n'); err == nil || len(line) > 0; line, err = buf.ReadString('\n') {
		l := line
		queue.Push(&l)
	}
	ss := queue.Stack(0, size, isDesc)
	for i := range ss {
		fmt.Print(*ss[i])
	}

	return
}
